package com.rent.view;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import com.mysql.fabric.xmlrpc.base.Array;
import com.rent.Impl.BrandDaoImpl;
import com.rent.Impl.CarDaoImpl;
import com.rent.Impl.RentDaoImpl;
import com.rent.Impl.TypeDaoImpl;
import com.rent.Impl.UserDaoImpl;
import com.rent.bean.Brand;
import com.rent.bean.Car;
import com.rent.bean.Rent;
import com.rent.bean.Type;
import com.rent.bean.User;
import com.rent.dao.BrandDao;
import com.rent.dao.CarDao;
import com.rent.dao.RentDao;
import com.rent.dao.TypeDao;
import com.rent.dao.UserDao;
import com.rent.utils.BaseDao;
import com.rent.utils.DataAccessUtils;
import com.rent.utils.ViewUtils;

/**
 * 选项
 * @author xin
 *
 */
public class Option {
	//视图工具类
	ViewUtils v = new ViewUtils();
	//汽车接口
	CarDao carDao = new CarDaoImpl();
	BaseDao baseDao = new BaseDao();
	Scanner sn = new Scanner(System.in);
	//订单接口
	RentDao rentDao = new RentDaoImpl();
	//用户接口
	UserDao userDao = new UserDaoImpl();
	//品牌接口
	BrandDao brandDao = new BrandDaoImpl();
	//型号接口
	TypeDao typeDao = new TypeDaoImpl();
	//调用日期格式化对象
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 查询车辆
	 */
	public void search_car(User u) {
		//存储结果
		List<Car> list = null;
		//存储条件
		Car car = new Car();
		//提出车辆同用户选择
		System.out.println("请选择：1、查询全部车；2、索引查询");
		//默认索引查询
		if(sn.nextInt()==2) {
			try {
				//这个作用把前面next方法的回车符接收一下
				sn.nextLine();
				System.out.println("请输入查询类别：（不输入可直接回车）");
				System.out.println("车辆编号：");
				String carid = sn.nextLine();
				if(!carid.isEmpty()) {
					car.setCarid(Integer.parseInt(carid));					
				}
				System.out.println("车辆品牌（会员专属：宝马/东风/奔驰）大众/丰田/本田）：");
				String cbrand = sn.nextLine();
				if(!cbrand.isEmpty()) {
					car.setCbrand(cbrand);
				}
				System.out.println("车辆型号：");
				String ctype = sn.nextLine();
				if(!ctype.isEmpty()) {
					car.setCtype(ctype);
				}
				System.out.println("车辆颜色：");
				String color = sn.nextLine();
				if(!color.isEmpty()) {
					car.setColor(color);
				}
				System.out.println("价格（元/小时）<");
				String cprice = sn.nextLine();
				if(!cprice.isEmpty()) {
					car.setCprice(Double.parseDouble(cprice));
				}
				
			} catch (NumberFormatException e) {
				System.out.println("输出错误!");
				return;
			} 
			v.show_car(carDao.sele_car(u.getPower(), car));
		}else {
			List<Brand> brands = brandDao.seleAll(u.getPower());
			for(Brand b : brands) {
				v.printTitle("品牌："+b.getBrand());
				List<Type> types = typeDao.seleByBrand(b.getBrand(),u.getPower());
				for(Type t : types) {
					v.printTitle("型号："+t.getType());
					car.setCtype(t.getType());
					car.setCbrand(b.getBrand());
					List<Car> cars = carDao.sele_carByType(u.getPower(), car);
					v.show_car_type(cars);
				}
				System.out.println();
			}
		}
	}
	/**
	 * 租赁车辆
	 * @param u
	 */
	public void rent(User u) {
		Car c = new Car();
		System.out.println("1.查询品牌型号 2.查询全部");
		switch (sn.nextInt()) {
		case 1:
			v.show_brand(brandDao.seleByBrand(null));
			System.out.println("请输入你想租赁的品牌");
			c.setBid(sn.nextInt());
			Brand brand = brandDao.seleById(c.getBid());
			if(brand==null) {
				System.out.println("没有这个品牌");
				return;
			}
			c.setCbrand(brand.getBrand());
			Type t = new Type();
			t.setBid(c.getBid());
			List<Type> types = typeDao.seleByType(t);
			v.show_type(types);
			System.out.println("请选择型号：");
			c.setTid(sn.nextInt());
			Type type = typeDao.seleById(c.getTid());
			if(type==null) {
				System.out.println("没有这个型号");
			}
			c.setCtype(type.getType());
			v.show_car(carDao.sele_car(u.getPower(), c));
			break;
		case 2:
			v.show_car(carDao.sele_car(u.getPower(), c));
			break;
		}
		rent_info(u);
	}
	/**
	 * 输入基本信息
	 */
	public void rent_info(User u) {
		Rent r = new Rent();
		Car car = null;
		//获取现在时间
		Date tdate = new Date();
		tdate.setMinutes(tdate.getMinutes()+20);
		try {
			//接收前面缓存
			System.out.println("请输入租赁车辆：");
			car = carDao.seleById(sn.nextInt());
			Car seleById = null;
			try {
				seleById = carDao.seleById(car.getCarid());
			} catch (Exception e1) {
				System.out.println("没有此车辆！");
				return;
			}
			if(seleById.getCstatus()!=1) {
				System.out.println(seleById.getCarid()+"号汽车 "+seleById.getStatus_detailed()+",无法租赁");
				return;
			};
			sn.nextLine();
			Date before = tdate;
			Date after = new Date();
			after.setDate(after.getDate()+2);
			after.setHours(12);
			after.setMinutes(0);
			after.setSeconds(0);
			System.out.println("租赁天数不能超过3个月（90天），租赁时常不能少于3小时，\n早上8：00~晚上8点为营业时间\n取车日期在 "+simpleDateFormat.format(tdate)+" 和 "+simpleDateFormat.format(after)+"之间");
			System.out.println("请输入取车时间：");
			r.setRtime(sn.nextLine());
			System.out.println("请输入还车时间：");
			r.setBtime(sn.nextLine());
			//计算价格 
			//将字符串转换为日期类型
			Date rdate = null;
			Date bdate = null;
			try {
				rdate = simpleDateFormat.parse(r.getRtime());
				bdate = simpleDateFormat.parse(r.getBtime());
				if(tdate.after(rdate)) {
					throw new Exception("取车日期必须在 "+simpleDateFormat.format(tdate)+" 之后");
				}
				if(rdate.after(after)) {
					throw new Exception("取车日期必须在 "+simpleDateFormat.format(after)+" 之前");
				}
				if(rdate.after(bdate)) {
					throw new Exception("归还日期不能在取车日期之前！");
				}
				rdate.getTime();
				if(((bdate.getTime()-rdate.getTime())/1000/60/60)<3) {
					throw new Exception("租赁时常不能少于3小时");
				}
				if(rdate.getHours()<8||rdate.getHours()>19) {
					throw new Exception("请在营业时间(8:00~20:00)内取车");
				}
				if(bdate.getHours()<8||bdate.getHours()>19) {
					throw new Exception("请在营业时间(8:00~20:00)内还车");
				}
			} catch (ParseException e) {
				System.out.println("输入日期不合法，请重新输入！");
				e.printStackTrace();
				return;
			}
			long hours = (bdate.getTime()-rdate.getTime())/1000/60/60;
			if(tdate.after(rdate)) {
				System.out.println("您输入的日期");
			}
			if(hours/24>90) {
				System.out.println("租赁天数不能超过3个月（90天）");
			}
			double money = (car.getCprice()*hours);
			//会员用户打九折
			if(u.getPower()==2) {
				System.out.println("会员用户打九折 原价："+money+"\t现价:"+money * 0.9);
				money = money * 0.9;
			}
			//汽车押金+违章押金+（租赁小时数*汽车价格） 
			r.setMoney(money);
			r.setCar_deposit(car.car_deposit);
			r.setViolation_deposit(car.violation_deposit);
			r.setUname(u.getUname());
			r.setCid(car.getCarid());
			r.setStatus(1);
			//增加订单
			rentDao.add(r);
			System.out.println("预约成功！请在提前半小时在"+simpleDateFormat.format(rdate)+"之前取车");
			//把汽车的状态修改为租出
			car.setCstatus(2);
			carDao.updateStatusById(car);
			pay_rent(u);
		} catch (Exception e1) {
			System.out.println("输入不合法！请重新输入");
			e1.printStackTrace();
		}
		
	}
	
	/**
	 * 查看自己的订单
	 */
	public void show_rent(User u) {
		v.show_rent(rentDao.sele(u));
		System.out.println("1.取消订单 2.还车 3.查看订单详细");
		switch (sn.nextInt()) {
		case 1:
			cancel(u);
			break;
		case 2:
			returnCar(u);
			break;
		case 3:
			rentDetailed();
			break;
		}
	}
	
	//查看详细租赁信息
	public void rentDetailed() {
		System.out.println("请输入编号：");
		Rent rent = rentDao.seleById(sn.nextInt());
		if(rent==null) {
			System.out.println("没有此租赁信息");
			return;
		}
		Car car = carDao.seleById(rent.getCid());
		v.show_rent(rent, car);
		
	}
	
	/**
	 * 租赁还是归还
	 */
	public void leaseOrReturn(User u){
		//根据用户编号查询有没有租赁中车辆
		Rent r = null;
		List<Rent> list = rentDao.seleStatusByUname(u.getUname());
		if(list.size()>1) {
			try {
				throw new Exception("订单异常！");
			} catch (Exception e) {		
				e.printStackTrace();
			}
		}
		if(!list.isEmpty()) {
			r = list.get(0);
			switch (r.getStatus()) {
			case 3:
				//用户车辆租赁中
				returnCar(u);
				break;
			case 1:
				//用户有订单未支付
				pay_rent(u);
				break;
			case 2:
				//用户没有提车
				getCar(u);
				break;
			default:
				break;
			}
		}else {
			//没有租赁中车辆
			rent(u);
		}
	}
	/**
	 * 归还车辆
	 * @param u
	 */
	public void returnCar(User u) {
		/*
		 * 归还车辆时 需要提前归还车辆时应先提前预约，归还时间一小时内可以归还，超时半小时不收取任何费用
		 * 归还时间2020 12-1-1 19：00：00 
		 * 归还时间为2020 12-1-1 18：30：00前需要提前预约 
		 * 归还时间为：2020 12-1-1 19：30：00 后需要缴纳超时费
		 */
		u = userDao.sele_nameAndpwd(u.getUname(),u.getUpassword());
		List<Rent> l = rentDao.seleStatusByUname(u.getUname());
		Rent r = null;
		if(!l.isEmpty()) {
			v.printTitle("神州租车-还车");
			System.out.println("你有车辆未归还，是否归还？(y/n)");
			switch (sn.next()) {
			case "y":
				if(l.size()>1) {
					try {
						throw new Exception("订单异常");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				Rent rentshow = l.get(0);
				Car carshow = carDao.seleById(rentshow.getCid());
				v.show_rent(rentshow, carshow);
				r = l.get(0);
				Date btime = null;
				try {
					btime = simpleDateFormat.parse(r.getBtime());
				} catch (ParseException e) {
					e.printStackTrace();
				}
				Car rent_car = carDao.seleById(r.getCid());
				Car c = new Car();
				Date thisDate = new Date();
				long time = btime.getTime()-thisDate.getTime();
				double money = 0;
				double getMoney = 0;
				//判断是否超时
				if(time>0) {
					/*
					 * 提前3小时还车，退还相应的金额
					 * 3小时内归还则不退还金额
					 */
					long h=time/1000/60/60;//时
					long m=time/1000/60%60;//分
					if(time>3) {
						if(m>1) {
							h--;
						}
						money = rent_car.getCprice()*h;
						System.out.println("提前三小时归还，汽车使用时间不够一小时按照一小时收取"); 
						if(u.getPower()==2) {
							money = money*0.9;
						}
						getMoney = r.getMoney()-money;
						System.out.println(money+"￥和汽车押金一起退还到您的帐户");
						r.setCar_deposit(r.getCar_deposit()+money);
					}else {
						/*
						 * 三小时内归还则不退还费用
						 */
						System.out.println("3小时内归还"); 
					}
				}else {
					//归还时间之后归还
					long h = time/-1/1000/60/60;//时
					long m = time/-1/1000/60%60;//分
					System.out.println("您还车时间比预定时间晚 "+h+"小时,"+m+"分钟");
					if(time>1) {
						System.out.println("一小时内，不收取超时费");
					}else {
						System.out.println("一小时外，将收取一定的超时费，每小时按照租赁价格的两倍收取，不够一小时按照一小时收取");
						if(m>1) {
							h++;
						}
						money = rent_car.getCprice()*h*2;
						getMoney = r.getMoney()+money;
						System.out.println("将从您的押金扣除"+money+"￥");
						r.setCar_deposit(r.getCar_deposit()-money);
					}
				}
				//还车时间
				System.out.println(simpleDateFormat.format(thisDate));
				System.out.println(getMoney);
				r.setBtime(simpleDateFormat.format(thisDate));
				//收款金额
				r.setMoney(getMoney);
				System.out.println("赁前油量："+rent_car.getGasolineActualVolume());
				System.out.println("还车油量：");
				c.setGasolineActualVolume(sn.nextInt());
				//获取油量
				int volume = rent_car.getGasolineActualVolume()-c.getGasolineActualVolume();
				/*
				 * 根据用户的汽车油量，
				 * 多出的油量根据市场价格返还用户相应金额
				 * 如换车少油根据市场价格计算，相应减少租车的押金
				 * 
				 */
				if(volume!=0) {
					System.out.println("今日"+rent_car.getGasolineNumber()+"油价：");
					//计算出来的汽油价格
					double gasolineMoney = volume*sn.nextDouble();
					if(gasolineMoney<0) {
						gasolineMoney = (gasolineMoney/-1);
						System.out.println(gasolineMoney+"￥,金额会和押金一起退还");
						//向个人账户添加金额
						r.setCar_deposit(r.getCar_deposit()+gasolineMoney);
					}else {
						//获取帐户余额
						System.out.println("从您的个人押金内扣除，"+gasolineMoney+"￥");
						r.setCar_deposit(r.getCar_deposit()-gasolineMoney);
					}
				}
				System.out.println("车辆是否损坏(y/n)：");
				switch (sn.next()) {
				case "y":
					//车辆损坏押金先不退 
					System.out.println("汽车损坏，押金暂时不退");
					rent_car.setCstatus(3);
					break;
				case "n":
					//退还押金
					if(r.getCar_deposit_status()==0) {
						r.setCar_deposit_status(1);
						System.out.println("将退还您汽车的押金是："+r.getCar_deposit()+"￥");
					}else {
						System.out.println("押金已经退还");
					}
					break;
				default:
					System.out.println("输入不合法");
					return;
				}
				//修改状态为完成
				r.setStatus(4);
				System.out.println("违章押金将在两周内返还到您的帐户");
				//修改汽车的状态
				rent_car.setCstatus(1);
				carDao.updateStatusById(rent_car);
				//开启还车事务
				rentDao.rentCar(r);
				//修改油箱
				carDao.updateGasolineActualVolume(c);
				break;
			}
		}else {
			System.out.println("您没有预约");
		}
	}
	/**
	 * 支付
	 * @param u
	 */
	public void pay_rent(User u) {
		v.printTitle("神州租车-支付");
		//先展示未支付订单
		List<Rent> l = rentDao.seleByUname(u.getUname(),1);
		if(l.size()>1) {
			try {
				throw new Exception("订单异常");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Rent rentshow = l.get(0);
		Car carshow = carDao.seleById(rentshow.getCid());
		v.show_rent(rentshow, carshow);
		//判断时间是否过去
		Date thisdate = new Date();
		Date rdate = null;
		try {
			rdate = simpleDateFormat.parse(rentshow.getRtime());
			if(rdate.before(thisdate)) {
				rentDao.cancel(rentshow);
				System.out.println("\n订单超时，已取消！");
				return;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(!l.isEmpty()) {
			Rent r = l.get(0);
			u = userDao.selectByName(u.getUname());
			System.out.println("是否支付?(y/n)");
			switch (sn.next()) {
			case "y":
				//修改帐户余额
				if(u.getBalance()<(r.getMoney()+r.getViolation_deposit()+r.getCar_deposit())) {
					System.out.println("余额不足！");
				}else {
					try {
						//扣除金额 汽车租赁价格，汽车押金，违章押金
						u.setBalance(u.getBalance()-r.getMoney()-r.getCar_deposit()-r.getViolation_deposit());
						userDao.updateMoneyByUname(u);
						r.setStatus(2);
						rentDao.updateStatusByUname(r);
						System.out.println("支付成功！其中有：");
						System.out.println("汽车押金："+r.getCar_deposit());
						System.out.println("违章押金："+r.getViolation_deposit());
						System.out.println("租赁费用："+r.getMoney());
						System.out.println("余额剩余："+u.getBalance());
					} catch (Exception e) {
						System.out.println("支付异常");
					}	
				}
				break;
			}
		}
	}
	
	/**
	 * 订单取消
	 * @param u
	 */
	public void cancel(User u) {
		v.printTitle("神州租车-取消订订单");
		//获取到用户的未支付和未提车的订单
		List<Rent> l = rentDao.seleStatusByUname(u.getUname());
		Rent r = null;
		if(l.size()>1) {
			try {
				throw new Exception("订单异常");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Rent rentshow = l.get(0);
		Car carshow = carDao.seleById(rentshow.getCid());
		v.show_rent(rentshow, carshow);
		if(!l.isEmpty()) {
			r= l.get(0);
			if(r.getStatus()==1||r.getStatus()==2) {
				System.out.println("确定要取消订单吗?(y/n):");
				switch (sn.next()) {
				case "y":
					rentDao.cancel(r);
					Car c = carDao.seleById(r.getCid());
					System.out.println("订单取消成功!");
					break;
				}
			}else {
				System.out.println("租赁中的订单无法取消！");
			}
		}
	}
	/**
	 * 取车
	 * @param u
	 */
	public void getCar(User u) {
		//展示租赁的车辆
		List<Rent> l = rentDao.seleByUname(u.getUname(),2);
		if(l.size()>1) {
			try {
				throw new Exception("订单异常");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Rent rentshow = l.get(0);
		Car carshow = carDao.seleById(rentshow.getCid());
		v.show_rent(rentshow, carshow);
		if(!l.isEmpty()) {
			v.printTitle("神州租车-取车");
			Rent r = l.get(0);
			Car rent_car = carDao.seleById(r.getCid());
			if(r.getStatus()==2) {
				/*
				 * 客户取车时，判断时间，在预约的取车时间半小时内不收取额外费用
				 * 超过半小时，则按照现在取车时间再额外收取费用(不够一小时按照一小时收取费用)
				 */
				Date rdate = null;
				try {
					rdate = simpleDateFormat.parse(r.getRtime());
					Date thisDate = new Date();
					Date after = rdate;
					if(thisDate.before(after)) {
						long time = after.getTime()-thisDate.getTime();
						long h = time/1000/60/60;
						long m = time/1000/60%60;
						if(h<2) {
							System.out.println("距离取车时间两小时内， 可以正常取车");
						}else {
							System.out.println("来早了"+h+"小时"+m+"分钟");
							System.out.print("把车取走的话会将取车时间调整到现在，也会增加相应的费用,是否取车？(y/n)");
							switch (sn.next()) {
							case "y":
								//计算价格
								double money = rent_car.getCprice()*h;
								if(u.getBalance()<money) {
									System.out.println("余额不足，请重新充值");
									return;
								}
								Rent update = new Rent();
								update.setRid(r.getRid());
								update.setUname(r.getUname());
								update.setRtime(simpleDateFormat.format(thisDate));
								update.setMoney(money);
								System.out.println("把您的取车时间该到了"+simpleDateFormat.format(thisDate)+",总支付:"+(money+r.getMoney()));
								rentDao.rentUpdateRtime(update);
								break;
							}
						}
					}
					if(after.before(thisDate)){
						long time = thisDate.getTime()-after.getTime();
						long h = time/1000/60/60;
						long m = time/1000/60%60;
						if(h==0&&m<=10) {
							System.out.println("来的稍微有点晚，订单保存10分钟");
						}else {
							System.out.println("来晚了"+h+"小时"+m+"分钟");
							System.out.println("来晚了，订单取消了");
							rentDao.cancel(r);
							return;
						}
					}
				} catch (ParseException e) {
					System.out.println("日期格式不正确");
					e.printStackTrace();
				}
				System.out.println("车况是否完好？(y/n)");
				switch (sn.next()) {
				case "n":
					System.out.println("车况不不完好，订单已取消");
					rent_car.setSeat(3);
					rentDao.cancel(r);
					rent_car.setCstatus(3);
					carDao.updateStatusById(rent_car);
					break;
				case "y":
					System.out.println("取车成功，祝您出行平安!");
					r.setStatus(3);
					rentDao.updateStatusByUname(r);
					break;
				default:
					System.out.println("输入不合法！");
					break;
				}
			}else if(r.getStatus()==1) {
				System.out.println("订单未支付");
				pay_rent(u);
			}
		}
		
	}
	
}











